package com.authine.cloudpivot.web.api.advice;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.engine.enums.type.OperatorType;
import com.authine.cloudpivot.web.api.enums.Option;
import com.authine.cloudpivot.web.api.util.AuthUtils;
import com.authine.cloudpivot.web.api.view.PageVO;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.runtime.FilterVO;
import com.authine.cloudpivot.web.api.view.runtime.QueryDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2022/2/7 16:51
 * @Description
 **/
@Slf4j
@Aspect
@Component
public class CourseListAspect {

    @Autowired
    BizObjectFacade bizObjectFacade;

    /**
     * Pointcut 切入点
     *
     */
    @Pointcut("execution(* com.authine.cloudpivot.web.api.controller.runtime.QueryRuntimeController.list(..))")
    public void theAspect(){}



    /**
     * 环绕通知
     */
    @Around(value = "theAspect()")
    public Object arround(ProceedingJoinPoint pjp) throws Throwable {

        Object[] args = pjp.getArgs();

        String schemaCode=null,queryCode = null;
        QueryDataVO queryDataVO = null;
        if (args != null && args.length > 0) {
            queryDataVO = (QueryDataVO) args[0];
            schemaCode = queryDataVO.getSchemaCode();
            queryCode = queryDataVO.getQueryCode();

        }


        if ("kcqd".equals(schemaCode)    ){

            if ("courseCenter".equals(queryCode) || "myStudies".equals(queryCode)){
                String userId = AuthUtils.getUserId();
                log.info("\n=============进入 课程中心数据处理");
                //添加请求参数
                if ("myStudies".equals(queryCode) && queryDataVO != null){

                    BizObjectQueryModel queryModel = new BizObjectQueryModel();
                    queryModel.setSchemaCode("myStudy");
                    queryModel.setQueryCode("myStudy");
                    queryModel.setPageable(new PageableImpl(0,1000));
                    FilterExpression.Item it =  Q.it("creater", FilterExpression.Op.Eq,  userId);
                    queryModel.setFilterExpr(it);
                    Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(queryModel);

                    if (page.getTotal()>0){
                        List<FilterVO> filters = queryDataVO.getFilters();
                        if (filters == null){
                            filters = new ArrayList<>();
                        }

                        String courseIds = page.getContent().stream().map(bizObjectModel -> {
                            Map<String, Object> course = (Map<String, Object>) bizObjectModel.getObject("course");
                            return (String) course.getOrDefault("id", "");
                        }).collect(Collectors.joining());

                        FilterVO filterVO = new FilterVO();
                        filterVO.setPropertyCode("id");
                        filterVO.setOp(Option.In);
                        filterVO.setPropertyType(BizPropertyType.SHORT_TEXT);
                        filterVO.setPropertyValue(courseIds);
                        filters.add(filterVO);


                    }else {
                        return pjp.proceed();
                    }


                }
                Object proceed = pjp.proceed();
                ResponseResult<PageVO<BizObjectModel>>  result = (ResponseResult<PageVO<BizObjectModel>>)proceed;
                // 处理返回内容
                if (0l==result.getErrcode()){
                    List<String> collect = result.getData().getContent().stream().map(BizObjectModel::getId).collect(Collectors.toList());

                    BizObjectQueryModel queryModel = new BizObjectQueryModel();
                    queryModel.setSchemaCode("liked");
                    queryModel.setQueryCode("liked");
                    if (CollectionUtils.isEmpty(collect)) {
                        collect.add(null);
                    }
                    queryModel.setPageable(new PageableImpl(0,collect.size()));
                    List<FilterExpression> itList = new ArrayList<>();
                    FilterExpression.Item it = Q.it("courseId", FilterExpression.Op.In, collect);
                    itList.add(it);


                    it = Q.it("creater", FilterExpression.Op.Eq,  userId);
                    itList.add(it);
                    FilterExpression.And and = Q.and(itList);

                    queryModel.setFilterExpr(and);
                    Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(queryModel);

                    if (page.getTotal()>0){
                        log.info("\n=============已点赞处理");
                        List<String> courseIdList = page.getContent().stream().map(biz->biz.getString("courseId")).collect(Collectors.toList());

                        result.getData().getContent().stream().forEach(biz->biz.put("sfydz",courseIdList.contains(biz.getId())));
                    }else {
                        log.info("\n=============已点赞处理:未获取到已点赞数据:bizIds:{},userId:{}", JSON.toJSONString(collect),userId);
                    }

                    //已学习处理
                    BizObjectQueryModel queryModel2 = new BizObjectQueryModel();
                    queryModel2.setSchemaCode("myStudy");
                    queryModel2.setQueryCode("myStudy");
                    queryModel2.setPageable(new PageableImpl(0,collect.size()));
                    List<FilterExpression> itList2 = new ArrayList<>();
                    FilterExpression.Item it2 = Q.it("couseIdAndUserId", FilterExpression.Op.In, collect);
                    itList2.add(it2);


                    it2 = Q.it("creater", FilterExpression.Op.Eq,  userId);
                    itList2.add(it2);
                    FilterExpression.And and2 = Q.and(itList2);

                    queryModel2.setFilterExpr(and2);
                    Page<BizObjectModel> page2 = bizObjectFacade.queryBizObjects(queryModel2);

                    if (page2.getTotal()>0){
                        log.info("\n=============已学习处理");
                        List<String> courseIdList2 = page2.getContent().stream().map(biz->biz.getString("couseIdAndUserId")).collect(Collectors.toList());

                        result.getData().getContent().stream().forEach(biz->  biz.put("drsfxr",courseIdList2.contains(biz.getId())));
                    }else {
                        log.info("\n=============已学习处理:未获取到已学习数据:bizIds:{},userId:{}", JSON.toJSONString(collect),userId);
                    }
                }

                return proceed;
            }
        }

        return pjp.proceed();

    }
}
